package com.pingancar.creditmanage.service;

import com.pingancar.creditmanage.dao.CashDaoImpl;
import com.pingancar.creditmanage.dao.OrderitemDaoImpl;
import com.pingancar.creditmanage.dao.ShopInfoDaoImpl;
import com.pingancar.creditmanage.dao.ShopUserDaoImpl;
import com.pingancar.creditmanage.pojo.*;
import com.pingancar.creditmanage.util.JSONReceiver;
import com.pingancar.creditmanage.util.LBSMessage;
import com.pingancar.creditmanage.util.myenum.ShopInfoField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2014/9/6 0006.
 */
@Service
public class ShopServiceImpl {
    @Autowired
    ShopUserDaoImpl shopUserDao;
    @Autowired
    ShopInfoDaoImpl shopInfoDao;
    @Autowired
    OrderitemDaoImpl orderitemDao;
    @Autowired
    CashDaoImpl cashDao;

    public ShopuserPojo login(ShopuserPojo shopUserPojo) {
        if(!checkUser(shopUserPojo)){
            return null;
        }
        List<ShopuserPojo> result=shopUserDao.findByProperty("username", shopUserPojo.getUsername());

        if(result == null || result.isEmpty()){
            return null;
        }

        if(result.get(0).getPasswd().equals(shopUserPojo.getPasswd())){
            return result.get(0);
        }

        return null;
    }

    public boolean addShopInfo(ShopinfoPojo shopInfoPojo) {
        shopInfoDao.save(shopInfoPojo);
        return true;
    }

    public ShopinfoPojo updateShopInfo(ShopinfoPojo shopInfoPojo) {
        ShopinfoPojo re = shopInfoDao.load(shopInfoPojo.getId());
        if (re == null)
            return null;
        boolean same = true;
        if (!re.getName().equals(shopInfoPojo.getName()) || !re.getLocation().equals(shopInfoPojo.getLocation()))
            same = false;
        re.setBh(shopInfoPojo.getBh());
        re.setCon(shopInfoPojo.getCon());
        re.setName(shopInfoPojo.getName());
        re.setDescription(shopInfoPojo.getDescription());
        re.setLocation(shopInfoPojo.getLocation());
        shopInfoDao.update(re);

        if (!same) {
            LBSMessage lbsMessage = new LBSMessage();
            lbsMessage.setCoord_type(3);
            lbsMessage.setTitle(re.getName());
            lbsMessage.setAddress(re.getLocation());
            lbsMessage.setId(re.getLbs());

            JSONReceiver.updataPOI(lbsMessage);
        }

        return re;
    }

    public boolean deleteShopInfo(ShopinfoPojo shopInfoPojo) {
        List <ShopinfoPojo> result= shopInfoDao.findByProperty("shopid", shopInfoPojo.getShopid());
        if(result == null){
            result = new ArrayList<ShopinfoPojo>();
        }
        if(result.size()<1){
            return false;
        }
        shopInfoDao.delete(result.get(0));
        return false;
    }

    public boolean addShopUser(ShopinfoPojo shopinfoPojo, String username) {
        ShopuserPojo shopuserPojo = new ShopuserPojo();
        shopuserPojo.setShopinfo(shopinfoPojo);
        shopuserPojo.setPasswd("123456");
        shopuserPojo.setUsername(username);
        if(!checkUser(shopuserPojo)){
            return false;
        }
        List<ShopuserPojo> result=shopUserDao.findByProperty("username", shopuserPojo.getUsername());
        if(result != null && !result.isEmpty()){
            return false;
        }
        if (shopUserDao.save(shopuserPojo) != null)
            return true;
        return false;
    }

    public boolean updateShopUser(ShopuserPojo shopUserPojo) {
       List<ShopuserPojo> result= shopUserDao.findByProperty("shopid", shopUserPojo.getShopinfo().getId());
        if(result == null){
           return false;
        }
       if(result.size()<1){
           return false;
       }
        ShopuserPojo re= result.get(0);
        if(!shopUserPojo.getPasswd().equals("")){
            re.setPasswd(shopUserPojo.getPasswd());
        }
        if(!shopUserPojo.getUsername().equals("")){
            re.setUsername(shopUserPojo.getUsername());
        }
        if(!shopUserPojo.getUsername().equals("")){
            re.setUsername(shopUserPojo.getUsername());
        }
       shopUserDao.update(shopUserPojo);
        return true;
    }

    public boolean deleteShopUser(ShopuserPojo shopUserPojo) {
        List<ShopuserPojo> result= shopUserDao.findByProperty("shopid", shopUserPojo.getShopinfo().getId());
        if(result == null){
            result = new ArrayList<ShopuserPojo>();
        }
        if(result.size()<1){
            return false;
        }
        shopUserDao.delete(result.get(0));
        return true;
    }

    private boolean checkUser(ShopuserPojo shopUserPojo){
        //密码不能小于6位
        if(shopUserPojo.getPasswd().length()<6){
            return false;
        }
        //用户名不能小于4位
        if(shopUserPojo.getUsername().length()<4){
            return false;
        }
        //检验是否存在非法字符

        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        if(p.matcher(shopUserPojo.getPasswd()).find()||p.matcher(shopUserPojo.getUsername()).find()){
            return false;
        }

        return true;
    }

    public ShopinfoPojo getShopinfoByUser(ShopuserPojo shopuserPojo) {
        shopuserPojo = shopUserDao.load(shopuserPojo.getId());
        if (shopuserPojo == null)
            return null;
        return shopuserPojo.getShopinfo();
    }

    public ShopuserPojo updatePassword(ShopuserPojo shopuserPojo, String oldpw, String newpw) {
        shopuserPojo = shopUserDao.load(shopuserPojo.getId());
        if (shopuserPojo == null)
            return null;
        if (!shopuserPojo.getPasswd().equals(oldpw))
            return null;

        shopuserPojo.setPasswd(newpw);
        if (!checkUser(shopuserPojo))
            return null;
        shopUserDao.update(shopuserPojo);
        return shopuserPojo;
    }

    /**
     * 查询订单列表
     * @return
     */
    public List<OrderitemPojo> getOrderlistByShop(ShopinfoPojo shopinfoPojo, Integer offset, Integer len, Integer[] status) {
        return orderitemDao.getOrderlistByShop(shopinfoPojo, offset, len, status);
    }

    /**
     * 按order编号查找
     * @param orderitemid
     * @param shopinfoPojo
     * @return
     */
    public OrderitemPojo getOrderByOrderid(String orderitemid, ShopinfoPojo shopinfoPojo) {
        List<OrderitemPojo> l = orderitemDao.findByProperty("orderitemid", orderitemid);
        if (l == null || l.isEmpty())
            return null;

        OrderitemPojo orderitemPojo = l.get(0);
        if (orderitemPojo.getPaservice().getShopinfo().getId() != shopinfoPojo.getId())
            return null;

        return orderitemPojo;
    }

    /**
     * 确认交易
     * @param shopinfoPojo
     * @param id
     * @return
     */
    public ShopinfoPojo confirmOrder(ShopinfoPojo shopinfoPojo, Integer id) {
        if (shopinfoPojo == null)
            return null;

        OrderitemPojo orderitemPojo = orderitemDao.load(id);
        if (orderitemPojo == null)
            return null;

        orderitemPojo.setStatus(OrderitemPojo.CONFIRM);
        orderitemPojo.setConfirmtime(new Timestamp(new Date().getTime()));
        orderitemDao.update(orderitemPojo);

        shopinfoPojo.setCredit(shopinfoPojo.getCredit()+orderitemPojo.getCredit());
        shopinfoPojo.setOrdersum(shopinfoPojo.getOrdersum()+1);
        shopInfoDao.update(shopinfoPojo);

        return shopinfoPojo;
    }

    /**
     * 申请提现
     * @param shopinfoPojo
     * @return
     */
    public String cash(ShopinfoPojo shopinfoPojo) {
        if (shopinfoPojo == null)
            return "申请失败";

        if (shopinfoPojo.getCredit()==0)
            return "账户没有积分";

        CashPojo cashPojo = new CashPojo();
        cashPojo.setCredit(shopinfoPojo.getCredit());
        cashPojo.setShopinfo(shopinfoPojo);
        cashPojo.setApplytime(new Timestamp(new Date().getTime()));

        cashDao.save(cashPojo);

        shopinfoPojo.setCredit(0);
        shopInfoDao.update(shopinfoPojo);
        return "success";
    }
}
